import { Col, Form, Input, Modal, Row } from 'antd';
import React, { Component } from 'react';
import { isEmpty, isFunction, map, isObject } from 'lodash';
import router from 'umi/router';
import { createForm } from '/common/components/HocCRUD';
import PageItem from '/common/components/PageItem';


@Form.create()
@createForm()
class DetailForm extends Component {

  getAjaxData() {
    const { compData } = this.props;
    const detail = compData || {};
    return new Promise((resolve, reject) => {
      this.props.form.validateFieldsAndScroll((errors, fieldsValue) => {
        // console.log('fieldsValue', fieldsValue);
        if (isEmpty(errors)) {
          const values = {
            ...detail,
            ...fieldsValue,
          };
          resolve(values);
        } else {
          reject(errors);
        }
      });
    });
  }

  render() {
    const { compData } = this.props;
    const detail = compData || {};
    const formFields = [
      {
        label: '岗位编码',
        fieldName: 'code',
        options: {
          initialValue: detail.code,
          rules: [{
            required: true,
            message: '请输入岗位编码',
          }],
        },
        comp: <Input/>,
      },
      {
        label: '岗位名称',
        fieldName: 'name',
        options: {
          initialValue: detail.name,
          rules: [{
            required: true,
            message: '请输入岗位名称',
          }],
        },
        comp: <Input/>,
      },
    ];

    return (
      <Form layout="horizontal">
        <Row gutter={16}>
          {this.props.getFields(formFields)}
        </Row>
      </Form>
    );
  }
}

class PositionDetail extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
    this.itemRef = React.createRef();
  }

  async handleOk() {
    const {
      saveDetail,
    } = this.props;
    const itemRef = this.itemRef.current;

    if (itemRef && isFunction(itemRef.getAjaxData)) {
      try {
        const values = await itemRef.getAjaxData();
        saveDetail(values);
      } catch (e) {
        // console.log(e);
      }

    } else {
      console.error('PositionDetail Have not getAjaxData function');
    }
  };

  render() {
    return (
      <Modal
        width={520}
        title="新建岗位"
        visible={this.props.isShowDetail}
        keyboard={false}
        maskClosable={false}
        onOk={this.handleOk.bind(this)}
        onCancel={this.props.onCancel}
        destroyOnClose={true}
      >
        <DetailForm compData={this.props.detail}
                    wrappedComponentRef={this.itemRef}/>
      </Modal>
    );
  }
}

PositionDetail.propTypes = {};

export default PositionDetail;
